package com.gsn.poker.play;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Timeline;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.equations.Bounce;
import aurelienribon.tweenengine.equations.Cubic;
import aurelienribon.tweenengine.equations.Expo;
import aurelienribon.tweenengine.equations.Quart;
import aurelienribon.tweenengine.equations.Quint;
import aurelienribon.tweenengine.equations.Sine;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.actions.Delay;
import com.badlogic.gdx.scenes.scene2d.actions.FadeOut;
import com.badlogic.gdx.scenes.scene2d.actions.MoveTo;
import com.badlogic.gdx.scenes.scene2d.actions.Remove;
import com.badlogic.gdx.scenes.scene2d.actions.Sequence;
import com.badlogic.gdx.scenes.scene2d.ui.ClickListener;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.gsn.common.Settings;
import com.gsn.dataCommon.UserData;
import com.gsn.desktop.engine.ActorUtility;
import com.gsn.engine.gdx.GsnParticleActor;
import com.gsn.engine.myplay.GsnLayer;
import com.gsn.engine.template.GsnBubbleChat;
import com.gsn.engine.template.GsnEnableButton;
import com.gsn.engine.template.GsnNormalButton;
import com.gsn.engine.tween.ActorAccessor;
import com.gsn.engine.tween.GsnTween;
import com.gsn.poker.asset.PokerSound;
import com.gsn.poker.asset.PokerTexture;
import com.gsn.poker.game.DataProvider;
import com.gsn.poker.game.MyPoker;
import com.gsn.poker.logic.Card;
import com.gsn.poker.logic.CardGroupLogic;
import com.gsn.poker.packet.PacketFactory;

public class BoardLayer extends GsnLayer implements ClickListener {
	static final public String NHUONG_TO = "nhuong to";
	static final public String THEO = "theo";
	static final float TIME_DEAL_EFFECT = 0.7f;
	static final float TIME_DEAL_NEXT = 0.4f;
	static final public String TO = "to";
	static final public String TO_GAP_DOI = "to gap doi";
	static final public String TAKE_CHAIR = "take chair";

	static final public String TO_NUA = "to mot nua";
	static final public String TO_TAT_CA = "to tat ca";
	static final public String TO_TU = "to mot phan tu";
	static final public String UP_BO = "up bo";

	BetInfoGroup betInfo;
	BetTextGroup betText;
	Image bobai;
	GsnEnableButton[] btnArr = new GsnEnableButton[8];
	ButtonGroup btnGroupOne;
	ButtonGroup btnGroupTwo;
	ChipGroup chipGroup;

	int card1, card2;
	ArrayList<UserInfo> viewerListInfo;
	ImageButton chatBtn;

	ChonQuanGroup chonGroup;
	Image choNguoiKhacImg;

	ClockCountDown countClock;
	Image startGame;
	public boolean inGame = false;
	public boolean inAutoStart = false;

	Image logo;

	int minBet;

	public int myChair = -1;

	private int owner;

	float pad = 5;

	public PlayerGroup[] players = new PlayerGroup[5];
	ImageButton quitBtn;
	private int roomType; // 0: tap su, 1: nang cao

	ImageButton soundBtn;

	ImageButton startBtn;

	String tag = "Board Layer";

	long tong;
	private int roomId;
	public int roomBet;
	public int roomIndex;
	Label labelRoomIndex;
	boolean isNewGame = false;
	Image dotWait1;
	Image dotWait2;
	Image dotWait3;
	int countDot = 0;

	Image dotView1;
	Image dotView2;
	Image dotView3;
	int countDotView = 0;

	ImgTextGroup viewBtn;
	Image closeViewBtn;
	Image viewing;
	public PokerTexture pokerTexture;
	public boolean meViewToUser;

	public BoardLayer(float width, float height) {
		super(width, height);
		pokerTexture = PokerTexture.inst();
	}

	private void addBtn() {
		for (int i = 0; i < 8; i++) {
			switch (i) {
			case 0:
				btnArr[i] = new GsnEnableButton(i, TO, pokerTexture.inst().toBtn, pokerTexture.inst().toBtnDown, pokerTexture.inst().toBtnDisable);
				break;
			case 1:
				btnArr[i] = new GsnEnableButton(i, THEO, pokerTexture.inst().theoBtn, pokerTexture.inst().theoBtnDown, pokerTexture.inst().theoBtnDisable);
				break;
			case 2:
				btnArr[i] = new GsnEnableButton(i, NHUONG_TO, pokerTexture.inst().nhuongToBtn, pokerTexture.inst().nhuongToBtnDown, pokerTexture.inst().nhuongToBtnDisable);
				break;
			case 3:
				btnArr[i] = new GsnEnableButton(i, UP_BO, pokerTexture.inst().upboBtn, pokerTexture.inst().upboBtnDown, pokerTexture.inst().upboBtnDisable);
				break;
			case 4:
				btnArr[i] = new GsnEnableButton(i, TO_GAP_DOI, pokerTexture.inst().toGapDoiBtn, pokerTexture.inst().toGapDoiBtnDown, pokerTexture.inst().toGapDoiBtnDisable);
				break;
			case 5:
				btnArr[i] = new GsnEnableButton(i, TO_TAT_CA, pokerTexture.inst().toTatCaBtn, pokerTexture.inst().toTatCaBtnDown, pokerTexture.inst().toTatCaBtnDisable);
				break;
			case 6:
				btnArr[i] = new GsnEnableButton(i, TO_TU, pokerTexture.inst().toMotPhanTuBtn, pokerTexture.inst().toMotPhanTuBtnDown, pokerTexture.inst().toMotPhanTuBtnDisable);
				break;
			case 7:
				btnArr[i] = new GsnEnableButton(i, TO_NUA, pokerTexture.inst().toNuaBtn, pokerTexture.inst().toNuaBtnDown, pokerTexture.inst().toNuaBtnDisable);
				break;
			}
			btnArr[i].setAndSaveClickListener(this);
		}
		btnGroupOne = new ButtonGroup(btnArr[0], btnArr[1], btnArr[2], btnArr[3]);
		addActor(btnGroupOne);
		ActorUtility.setRatio(btnGroupOne, 0, 0, pad, pad);

		btnGroupTwo = new ButtonGroup(btnArr[4], btnArr[5], btnArr[6], btnArr[7]);
		addActor(btnGroupTwo);
		ActorUtility.setRatio(btnGroupTwo, 1, 0, width - pad, pad);

		closeViewBtn = new Image(pokerTexture.inst().viewBtn);
		viewBtn = new ImgTextGroup(closeViewBtn);
		ActorUtility.setCenter(viewBtn, btnGroupOne.x + btnGroupOne.width / 2, btnGroupOne.y + btnGroupOne.height * 0.75f);
		viewBtn.x = (width / 2 - players[0].width / 2 - viewBtn.width) / 2;
		viewBtn.y = (height / 2 - players[0].height / 2 - viewBtn.height) / 2;
		addActor(viewBtn);
		viewBtn.setClickListener(this);
		viewing = new Image(pokerTexture.inst().viewing);
		viewing.x = width / 2 + players[0].width / 2 + (width / 2 - players[0].width / 2 - viewing.width) / 2;
		viewing.y = viewBtn.y;
		addActor(viewing);
		dotView1 = new Image(pokerTexture.inst().dotWatch);
		dotView2 = new Image(pokerTexture.inst().dotWatch);
		dotView3 = new Image(pokerTexture.inst().dotWatch);
		dotView1.x = viewing.x + viewing.width * 0.75f;
		dotView2.x = dotView1.x + dotView1.width * 1.5f;
		dotView3.x = dotView2.x + dotView1.width * 1.5f;
		dotView3.y = dotView1.y = dotView2.y = viewing.y + viewing.height / 3;
		addActor(dotView1);
		addActor(dotView2);
		addActor(dotView3);
		updateToBtnGroup(false);
		if (myChair < 0)
			viewing.visible = true;
		else
			viewing.visible = false;

	}

	public void autoStart(int time) {
		stopAutoStart();

		inAutoStart = true;
		ActorUtility.setCenter(countClock, width * 0.5f, height * 0.7f);

		countClock.startTime(time);
		choNguoiKhacImg.visible = false;
		dotWait1.visible = false;
		dotWait2.visible = false;
		dotWait3.visible = false;

		addActor(startGame);
		addActor(countClock);

		if (myChair >= 0)
			viewBtn.visible = false;
		else
			viewBtn.visible = true;

	}

	public void baseInfo(JSONObject json) {
		try {
			roomId = json.getInt("roomID");
			long betMoney = json.getLong("moneyBet");
			if (betInfo != null) {
				// betInfo.remove();
				betInfo.updateMoney(betMoney);

			}
			// addActor(betInfo);
			// ActorUtility.setRatio(betInfo, 0, -0.2f, logo.x + logo.width,
			// logo.y);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void betMoney(JSONObject json) {
		try {
			final int chair = json.getInt("chair");
			int betType = json.getInt("betType");
			final long chipBet = json.getLong("chipBet");
			long totalTableBet = json.getLong("totalTableBet");
			// players[getChair(chair)].setText(" bet : " + betType + " ",
			// 1.5f);
			PlayerGroup p = players[getChair(chair)];
			p.updateMoney(p.getMoney() - chipBet);
			if (chair == myChair) {
				DataProvider.gold = p.getMoney();
			}
			PokerSound.playChipCrash();

			// Timer timer = new Timer();
			// final int _chair = getChair(chair);
			// timer.schedule(new TimerTask() {
			//
			// @Override
			// public void run() {
			// effectMoney(chair, -chipBet);
			//
			// }
			// }, (int) (1.5f * 1000));
			if (p.getMoney() == 0) {
				p.choiToiBen();
			} else {
				switch (betType) {
				case 0:
					p.to();
					break;
				case 1:
					p.toTatCa();
					break;
				case 2:
					p.toNua();
					break;
				case 3:
					p.toMotPhanTu();
					break;
				case 4:
					p.toGapDoi();
					break;
				case 5:
					p.theo();
					break;
				}
			}
			stopTime();
			updateBetText(getChair(chair), totalTableBet, chipBet);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void boLuot(int nChair) {
		players[getChair(nChair)].nhuongTo();

	}

	void updateToBtnGroup(boolean ok) {
		btnGroupOne.visible = ok;
		btnGroupTwo.visible = ok;

		if (myChair < 0) {
			viewing.visible = !ok;
			dotView1.visible = !ok;
			dotView2.visible = !ok;
			dotView3.visible = !ok;
		} else {
			viewing.visible = false;
		}

	}

	public void changeTurn(int playerTurn, int turnType) {
		// players[(playerTurn + 5 - myChair) % 5].setText("Chuyển Lượt", 1.5f);
		for (int i = 0; i < 5; i++)
			players[i].effQuaLuot();
		inGame = true;
		inAutoStart = true;
		choNguoiKhacImg.visible = false;
		effectTime(getChair(playerTurn), 15f);

		players[getChair(playerTurn)].effDenLuot();

		if (playerTurn == myChair) {
			updateToBtnGroup(true);
			updateBtn(turnType);

		} else {
			updateToBtnGroup(false);
		}
	}

	public void chatEmotion(JSONObject json) {
		try {
			int nChair = json.getInt("nChair");
			int index = json.getInt("emoIndex");
			players[getChair(nChair)].effectChat(3f, index);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	public void changeTurn(int playerTurn, JSONObject json) {
		try {
			int turnType = json.getInt("turnType");
			changeTurn(playerTurn, turnType);
			if (turnType == 1) {
				resetBetText();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void chat(int chair, String text) {
		if (chair < 0)
			return;
		GsnBubbleChat chatImg = null;
		PlayerGroup p = players[getChair(chair)];
		// text = "jasdfkasdfskdf asdjkfjasdkf asdkfsd kfask";
		switch (getChair(chair)) {
		case 0:
		case 3:
		case 4:
			chatImg = new GsnBubbleChat(pokerTexture.inst().bubbleChatTrai, 0.6f * p.width, pokerTexture.inst().fontLarge, text);
			ActorUtility.setRatio(chatImg, 0, 0.5f, p.x + p.avatar.x + p.avatar.width, p.y + p.avatar.y + p.avatar.height * 0.75f);
			break;
		case 1:
		case 2:
			chatImg = new GsnBubbleChat(pokerTexture.inst().bubbleChatPhai, 0.6f * p.width, pokerTexture.inst().fontLarge, text);
			ActorUtility.setRatio(chatImg, 1, 0.5f, p.x + p.avatar.x, p.y + p.avatar.y + p.avatar.height * 0.75f);
		}
		addActor(chatImg);
		chatImg.action(Delay.$(Remove.$(), 1.5f));
	}

	public float chia1vong(final int first, final int... idCard) {
		final float dur = TIME_DEAL_EFFECT;
		float time = 0;
		for (int i = 0; i < 5; i++)
			players[i].effQuaLuot();
		int count = 0;
		for (int i = 0; i < 5; i++) {

			final int tmp = i;

			if (players[getChair(first + i)].isAvailable() && !players[getChair(first + i)].isFold()) {

				Tween.call(new TweenCallback() {

					@Override
					public void onEvent(EventType type, BaseTween source) {
						Gdx.app.log("DKM play " + getChair(first + tmp), " quan card " + idCard[(first + tmp) % 5] + "  " + first + "   " + tmp);
						chiaBai(getChair(first + tmp), idCard[(first + tmp) % 5], dur);
					}
				}).delay(count * TIME_DEAL_NEXT).start(MyPoker.game.tweenManger);
				count++;
			}
		}
		for (int i = 0; i < players.length; i++)
			System.out.println("trang thai " + players[i].isAvailable());
		return count * TIME_DEAL_NEXT;

	}

	public void chia2LaDau() {
		float time = chia1vong(owner, 52, 52, 52, 52, 52);
		Tween.call(new TweenCallback() {

			@Override
			public void onEvent(EventType type, BaseTween source) {
				// TODO Auto-generated method stub
				chia1vong(owner, 52, 52, 52, 52, 52);
			}
		}).delay(time).start(MyPoker.game.tweenManger);
		// Timer timer = new Timer();
		//
		//
		// timer.schedule(new TimerTask() {
		//
		// @Override
		// public void run() {
		// chia1vong(owner, 52, 52, 52, 52, 52);
		//
		// }
		// }, (int) (1000 * time));
	}

	int cardIdHide;

	public void chiaBai(final int playerID, final int cardID, float duration) {
		// players[playerID].chiaBai(cardID, duration);
		if (cardID == 0)
			return;
		switch (playerID) {
		case 0:
			duration *= 2;
			break;
		case 1:
		case 4:
			duration *= 1.5f;
			break;
		case 2:
		case 3:
			duration *= 1;
			break;
		}
		PokerSound.playChiaBai();
		Gdx.app.log("Play ID " + playerID, "card id " + cardID + " numisdeal " + players[playerID].cardGroup.numIsDeal);

		try {
			Image card = new Image(pokerTexture.inst().baiUp);

			float x = players[playerID].x + players[playerID].cardGroup.x + players[playerID].cardGroup.cards[players[playerID].cardGroup.numIsDeal].x;
			float y = players[playerID].y + players[playerID].cardGroup.y + players[playerID].cardGroup.cards[players[playerID].cardGroup.numIsDeal].y;
			ActorUtility.setRatio(card, 0.5f, 1, width / 2, height);

			// card.action(Sequence.$(MoveTo.$(x, y, duration), Remove.$()));

			Tween.to(card, ActorAccessor.POS_XY, duration).target(x, y).ease(Quint.OUT).start(MyPoker.game.tweenManger);
			MyPoker.game.remove(card, duration);

			if (this.root.getActors().contains(chonGroup))
				this.root.addActorBefore(chonGroup, card);
			else
				addActor(card);

			Gdx.app.log("TANG DAN NUMISDEAL", "KHONG DUOC");
			players[playerID].cardGroup.numIsDeal++;

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		Tween.call(new TweenCallback() {
			@Override
			public void onEvent(EventType type, BaseTween source) {
				if (myChair >= 0 && roomType == 1 && playerID == 0 && players[0].getNumCard() == 4) {
					cardIdHide = cardID;
					players[playerID].addCardID(52);
					players[playerID].cardGroup.cards[4].setClickListener(BoardLayer.this);
				} else {
					players[playerID].addCardID(cardID);
					if (myChair >= 0 && playerID == 0) {
						players[playerID].hienBo(false, false);
					}
				}
			}
		}).delay(duration).start(MyPoker.game.tweenManger);
	}

	@Override
	public void click(Actor actor, float x, float y) {
		GsnParticleActor par = new GsnParticleActor(pokerTexture.inst().clickEff);
		Vector2 v = ActorUtility.getCoordinate(actor, x, y, this.root);

		par.setPostition(v.x, v.y);

		par.act(100000);
		addActor(par);
		par.start();

		if (actor == quitBtn) {
			PokerSound.playClick();
			Gdx.app.log(tag, "click menu Btn");
			if (inGame && myChair >= 0)
				((PlayScreen) screen).showQuitDlg();
			else {
				MyPoker.client.send(PacketFactory.createQuitRoom());
				MyPoker.game.setChooseRoomScreen();
				MyPoker.client.send(PacketFactory.getRefreshListTable());
			}
		} else if (actor == chatBtn) {
			Gdx.app.log(tag, "click chat");
			par.act(100000);
			par.remove();

			PokerSound.playClick();
			MyPoker.game.playScreen.showChatLayer();
		} else if (actor == startBtn) {
			MyPoker.client.send(PacketFactory.createRequestStart());
			PokerSound.playClick();
			startBtn.remove();
		} else if (actor == soundBtn) {
			Settings.enableSound = !soundBtn.isChecked();
			// effectJackpot(2000);

			PokerSound.playClick();
		} else if (actor == players[0].cardGroup.cards[4]) {
			players[0].cardGroup.cards[4].setId(cardIdHide);
			players[0].cardGroup.arrow.visible = false;
			// players[0].setDark(4, true);
			players[0].hienBo(false, false);
			players[0].cardGroup.cards[4].setClickListener(null);
		}
		if (actor instanceof GsnNormalButton) {
			String name = ((GsnNormalButton) actor).nameButton;
			Gdx.app.log(tag, "click button : " + name);
			PokerSound.playClick();
			if (name.equals(TO_NUA))
				MyPoker.client.send(PacketFactory.createTO(PacketFactory.TO_1_2));
			else if (name.equals(UP_BO))
				MyPoker.client.send(PacketFactory.createFold());
			else if (name.equals(TO_TAT_CA))
				MyPoker.client.send(PacketFactory.createTO(PacketFactory.TO_TAT_CA));
			else if (name.equals(TO_TU))
				MyPoker.client.send(PacketFactory.createTO(PacketFactory.TO_1_4));
			else if (name.equals(TO_GAP_DOI))
				MyPoker.client.send(PacketFactory.createTO(PacketFactory.TO_GAP_DOI));
			else if (name.equals(THEO))
				MyPoker.client.send(PacketFactory.createTO(PacketFactory.THEO));
			else if (name.equals(TO))
				MyPoker.client.send(PacketFactory.createTO(PacketFactory.TO));
			else if (name.equals(NHUONG_TO))
				MyPoker.client.send(PacketFactory.createNhuongTo(myChair));
			else if (name.equals(TAKE_CHAIR)) {
				MyPoker.client.send(PacketFactory.createTakeChair(((GsnNormalButton) actor).id));
			}
			updateToBtnGroup(false);
		}

	}

	private void hideEffPlayer() {
		for (int i = 0; i < 5; i++)
			if (!players[i].isFold())
				players[i].cardGroup.removeImg();
	}

	public void dealCard(JSONObject json) {
		try {
			hideEffPlayer();

			JSONArray cardIdArr = json.getJSONArray("cardID");
			final int first = json.getInt("firstTurnId");
			final int[][] arr = new int[3][5];
			int nCard = 0;
			boolean right = false;
			int random = 0;
			try {
				if (players[getChair(first)].isAvailable())
					right = true;
			} catch (Exception e) {
				// TODO: handle exception
				right = false;
			}

			for (int i = 0; i < cardIdArr.length(); i++) {
				if (cardIdArr.isNull(i))
					continue;
				JSONObject card = cardIdArr.getJSONObject(i);
				int n = card.getInt("nCard");
				if (nCard < n)
					nCard = n;
				// if (nCard == 0)
				// continue;
				JSONArray cardID = card.getJSONArray("cardID");
				for (int j = 0; j < 3; j++) {
					int tmp = cardID.getInt(j);
					if (tmp != 0 && right == false)
						random = i;
					arr[j][i] = tmp;
					// arr[j][i] = 40;
				}
			}

			float time = 0;
			for (int i = 0; i < nCard; i++) {
				final int tmp = i;
				final int _random = random;
				final boolean _right = right;
				MyPoker.game.call(new TweenCallback() {

					@Override
					public void onEvent(EventType type, BaseTween source) {
						if (_right)
							chia1vong(_random, arr[tmp]);
						else
							chia1vong(first, arr[tmp]);
					}
				}, time);
				if (_right)
					time += getTimeChia1vong(first, arr[tmp]);
				else
					time += getTimeChia1vong(random, arr[tmp]);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void effectMoney(int money) {
		Group a = CongTruTienGroup.convertNum(money, pokerTexture.inst().cong, pokerTexture.inst().tru, pokerTexture.inst().daucong, pokerTexture.inst().dautru, pokerTexture.inst().dauphaycong, pokerTexture.inst().dauphaytru);
		ActorUtility.setCenter(a, width / 2, height / 2);
		addActor(a);
		a.action(FadeOut.$(1.5f));
	}

	public void effectMoney(int chair, long money) {
		PlayerGroup p = players[getChair(chair)];
		p.effectMoney(money);
		// Gdx.app.log(tag, "effect vt : " + a.x + " " + a.y);

	}

	public void effectTime(int chair, float time) {
		stopTime();
		players[chair].effectTime(time);
	}

	public void endGame(JSONObject json) {
		try {
			isNewGame = false;
			inGame = false;
			inAutoStart = false;
			updateToBtnGroup(false);
			final JSONArray result = json.getJSONArray("resultType");
			stopTime();
			if (betText != null) {
				betText.visible = false;
			}
			for (int i = 0; i < 5; i++)
				players[i].effQuaLuot();

			if (myChair != -1) {
				if (!players[0].isFold() && players[0].getNumCard() == 5 && players[0].getCardID(4) == 52)
					players[0].cardGroup.cards[4].setId(cardIdHide);
			}
			MyPoker.game.call(new TweenCallback() {

				@Override
				public void onEvent(EventType type, BaseTween source) {
					try {

						for (int i = 0; i < result.length(); i++) {
							switch (result.getInt(i)) {
							case 1:
								players[getChair(i)].hienBo(true, true);
								players[getChair(i)].win();
								if (myChair >= 0 && i == myChair) {
									PokerSound.playThang();
								}
								break;
							case 2:
								if (players[getChair(i)].isAvailable() && !players[getChair(i)].isFold()) {
									players[getChair(i)].hienBo(false, true);
								}
								players[getChair(i)].lose();
								if (myChair >= 0 && i == myChair) {
									PokerSound.playThua();
								}

								break;
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}, 2f);

			// for (int i = 0; i < 5; i++) {
			// int type = result.getInt(i);
			// }
			final JSONArray chipGet = json.getJSONArray("chipGet");
			// if (myChair != -1) {
			// Gdx.app.log(tag, "nhan dc: " + chipGet.getInt(myChair));
			// effectMoney(chipGet.getInt(myChair));
			// }

			MyPoker.game.call(new TweenCallback() {
				@Override
				public void onEvent(EventType type, BaseTween source) {
					try {
						for (int i = 0; i < 5; i++) {
							final long tien = chipGet.getLong(i);
							if (tien != 0) {
								final int chair = getChair(i);
								ChipRandomGroup ani = new ChipRandomGroup(tien);
								ani.x = chipGroup.x;
								ani.y = chipGroup.y;
								ani.action(Sequence.$(MoveTo.$(players[chair].x + players[chair].width / 2, players[chair].y + players[chair].height / 2, 1f), Remove.$()));
								addActor(ani);
								chipGroup.setMoney(0);
							}
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			}, 5f);

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	public void fold(int nChair) {
		// players[(nChair + 5 - myChair) % 5].setText("FOLD", 3);
		players[(nChair + 5 - myChair) % 5].fold();
		System.out.println(" thang " + (nChair + 5 - myChair) % 5 + " fold ");
		stopTime();
	}

	public int getChair(int id) {
		return (id + 5 - myChair) % 5;
	}

	public int getID(int chair) {
		if (myChair == -1)
			return (chair + myChair + 5) % 5;
		return (chair + myChair) % 5;
	}

	public int getMyChair() {
		return myChair;
	}

	public int getNumberPlayer() {
		int count = 0;
		for (int i = 0; i < 5; i++)
			if (players[i].isAvailable())
				count++;
		return count;
	}

	public float getTimeChia1vong(final int first, final int... idCard) {
		final float dur = TIME_DEAL_EFFECT;
		float time = 0;
		for (int i = 0; i < 5; i++) {
			if (players[getChair(first + i)].isAvailable() && idCard[(first + i) % 5] != 0) {
				time += dur;
			}
		}
		return time;

	}

	Image nenLoai;

	public void init(boolean createPlayer) {
		MyPoker.game.tweenManger.killAll();
		this.clear();
		Image bg = new Image(pokerTexture.inst().board);
		bg.width = width;
		bg.height = height;
		addActor(bg);

		logo = new Image(pokerTexture.inst().logoXito);
		addActor(logo);
		ActorUtility.setRatio(logo, 0, 1.5f, 0, height);

		betInfo = new BetInfoGroup(10000);
		addActor(betInfo);
		ActorUtility.setRatio(betInfo, 0.5f, -0.1f, width / 4, logo.y);

		nenLoai = new Image(pokerTexture.inst().nenTapSu);
		addActor(nenLoai);
		ActorUtility.setCenter(nenLoai, width / 2, height * 0.75f);

		setRoomType(roomType);

		quitBtn = new ImageButton(pokerTexture.inst().quitBtn, pokerTexture.inst().quitBtnDown);
		ActorUtility.setRatio(quitBtn, 1f, 1f, width, height);
		addActor(quitBtn);
		quitBtn.setClickListener(this);

		soundBtn = new ImageButton(pokerTexture.inst().soundBtn, pokerTexture.inst().soundBtnDown, pokerTexture.inst().soundBtnOff);
		ActorUtility.setRatio(soundBtn, 1f, 1f, quitBtn.x, height);
		addActor(soundBtn);
		soundBtn.setClickListener(this);
		soundBtn.setChecked(!Settings.enableSound);

		chatBtn = new ImageButton(pokerTexture.inst().chatBtn, pokerTexture.inst().chatBtnDown);
		ActorUtility.setRatio(chatBtn, 1f, 1f, soundBtn.x, height);
		addActor(chatBtn);
		chatBtn.setClickListener(this);

		float heightMenu = logo.height + pad;
		if (createPlayer) {
			for (int i = 0; i < players.length; i++) {
				if (i == 1 || i == 2)
					players[i] = new PlayerGroup(1, this, i);
				else if (i == 0)
					players[i] = new PlayerGroup(0, this, i);
				else
					players[i] = new PlayerGroup(-1, this, i);
				addActor(players[i]);
			}

			ActorUtility.setRatio(players[0], 0.5f, 0, width / 2, 0.5f * heightMenu);
			// ActorUtility.setRatio(players[0], 0.5f, 0, width / 2, 0);
			ActorUtility.setRatio(players[1], 1f, 0.5f, width, (height - 2.2f * heightMenu) / 2 + 0.5f * heightMenu);
			ActorUtility.setRatio(players[2], 1f, 1f, width, (height - 1.7f * heightMenu));
			ActorUtility.setRatio(players[3], 0f, 1f, 0, (height - 1.7f * heightMenu));
			ActorUtility.setRatio(players[4], 0, 0.5f, 0, (height - 2.2f * heightMenu) / 2 + 0.5f * heightMenu);

			if (Settings.mode == 0) {
				players[0].setAvailable(true);
				players[1].setAvailable(true);
				players[2].setAvailable(true);
				players[3].setAvailable(true);
				players[4].setAvailable(true);

				UserInfo info = new UserInfo();
				info.name = "0";
				info.gold = 222222222;
				players[getChair(0)].setUserInfo(info);

				info.name = "1";
				players[getChair(1)].setUserInfo(info);

				info.name = "2";
				players[getChair(2)].setUserInfo(info);

				info.name = "3";
				players[getChair(3)].setUserInfo(info);

				info.name = "4";
				players[getChair(4)].setUserInfo(info);

				// for (int i = 0; i < 5; i++){
				// players[i].newGame();
				//
				// for (int j = 0; j < 5; j++){
				//
				// players[i].cardGroup.
				// }
				// }
				// updateBetText(0, 100, 200);

			}
		}

		// players[1].setAvailable(true);
		startBtn = new ImageButton(pokerTexture.inst().startBtn, pokerTexture.inst().startBtnDown);
		ActorUtility.setCenter(startBtn, width / 2, height / 2);
		startBtn.setClickListener(this);

		choNguoiKhacImg = new Image(pokerTexture.inst().chuChoNguoiKhac);
		ActorUtility.setCenter(choNguoiKhacImg, width / 2, height / 2);
		choNguoiKhacImg.visible = false;
		addActor(choNguoiKhacImg);
		dotWait1 = new Image(pokerTexture.inst().dotWait);
		dotWait2 = new Image(pokerTexture.inst().dotWait);
		dotWait3 = new Image(pokerTexture.inst().dotWait);
		dotWait1.x = choNguoiKhacImg.x + choNguoiKhacImg.width + dotWait1.width;
		dotWait2.x = dotWait1.x + dotWait1.width * 1.5f;
		dotWait3.x = dotWait2.x + dotWait1.width * 1.5f;
		dotWait3.y = dotWait1.y = dotWait2.y = choNguoiKhacImg.y + choNguoiKhacImg.height / 7;
		addActor(dotWait1);
		addActor(dotWait2);
		addActor(dotWait3);

		inGame = false;
		inAutoStart = false;

		addBtn();

		chipGroup = new ChipGroup();
		ActorUtility.setCenter(chipGroup, width / 2, height * 0.5f);
		addActor(chipGroup);

		labelRoomIndex = new Label("Bàn : " + roomIndex, new Label.LabelStyle(pokerTexture.inst().fontMedium, new Color(1, 1, 0, 1)));
		// labelRoomIndex = new GsnLabel("Bàn : " + roomIndex,
		// pokerTexture.inst().fontMedium, new Color(1, 1, 0, 1));
		ActorUtility.setRatio(labelRoomIndex, 0, -0.2f, width * 0.6f, logo.y);
		addActor(labelRoomIndex);
		betText = new BetTextGroup(0, 0);
		ActorUtility.setRatio(betText, 0.5f, 1f, width / 2, height / 2);
		addActor(betText);
		betText.visible = false;

		countClock = new ClockCountDown(pokerTexture.inst().start);
		ActorUtility.setCenter(countClock, width * 0.5f, height * 0.7f);
		startGame = new Image(pokerTexture.inst().afterTime);
		startGame.x = width * 0.5f - startGame.width * 0.5f;
		startGame.y = countClock.y + countClock.height * 1.5f;

		viewerListInfo = new ArrayList<UserInfo>();
	}

	Image chat;

	@Override
	public boolean keyDown(int keycode) {
		String s;
		JSONObject json;
		int count = 0;
		try {
			switch (keycode) {
			case Keys.F12:
				MyPoker.client.connect();
				break;

			case Keys.F11:
				init(true);
				break;
			case Keys.F1:
				// chia2LaDau();
				// showChonQuan(23, 25);

				// betInfo.updateMoney((int)(Math.random() * 200000));
				MyPoker.client.send(PacketFactory.createSelectRoom(0, ""));
				// MyPoker.client.send(PacketFactory.createCreateRoom());
				break;
			case Keys.F2:
				btnGroupOne.visible = true;

				btnGroupTwo.visible = true;
				// updateBtn(0);
				// chia2LaDau();
				// btnGroupOne.visible = true;
				// tinhtienPlayer(2);
				// MyPoker.client.send(PacketFactory.createCheatMoney(1000000000,
				// 100));
				// chia2LaDau();
				// showChonQuan(48, 34);

				break;
			case Keys.F7:
				showFirstCard(34, 35, 36, 52, 52);
				break;
			case Keys.F3:
				// s =
				// "{\"firstTurnId\":1,\"cmdID\":105,\"cardID\":[{\"nCard\":1,\"cardID\":[30,0,0]},{\"nCard\":1,\"cardID\":[38,0,0]},{\"nCard\":1,\"cardID\":[22,0,0]},{\"nCard\":0,\"cardID\":[0,0,0]},{\"nCard\":0,\"cardID\":[0,0,0]}]}";
				// json = new JSONObject(s);
				// dealCard(json);

				tinhtienPlayer(-1);
				break;
			case Keys.F4:
				s = " {\"card2\":[34,35,48,52,52],\"cmdID\":100,\"card1\":[37,21,36,52,52]}";
				json = new JSONObject(s);
				showPublicCard(json);
				break;
			case Keys.F5:
				updateBetText(2, 1242, 40);
				effectMoney(0, 100);
				break;
			case Keys.F6:
				s = "{\"bean\":10689,\"dogfall\":0,\"score\":734,\"lostCount\":0,\"winCount\":1,\"nChair\":0,\"coin\":3,\"cmdID\":50,\"escapeCount\":0}";
				json = new JSONObject(s);
				updateMoney(json);
				break;
			case Keys.F9:
				MyPoker.client.pause();
				break;
			case Keys.F10:
				MyPoker.client.resume();
				break;
			case Keys.A:
				effectThang(9, new CardGroupLogic(2, 3, 4, 5, 6));
				// players[1].visible = true;
				// players[1].effectChat(3f, 10);
				break;
			case Keys.S:
				effectJackpot(2000);
				break;
			case Keys.Q:
				chia1vong(2, 4, 4, 4, 4, 4);
				break;
			case Keys.W:
				CardGroupLogic group = new CardGroupLogic();
				CardGroupLogic kq = new CardGroupLogic();
				group.putCardIn(new Card(40));
				group.putCardIn(new Card(41));
				group.putCardIn(new Card(42));
				group.putCardIn(new Card(43));
				group.putCardIn(new Card(44));
				effectThang(7, group);
				break;
			case Keys.E:
				if (chat != null)
					chat.remove();
				chat = new Image(pokerTexture.inst().emo11);
				ActorUtility.setCenter(chat, 100, 100);
				addActor(chat);
				// Tween.to(img, ActorAccessor.CPOS_XY, 1).target(100, img.y -
				// 5).ease(Bounce.INOUT).repeatYoyo(1,
				// 0).start(GsnTween.manager);
				chat.scaleY = 1f;
				float time = 0.5f;
				// Tween.to(img, ActorAccessor.SCALE_XY, time).target(1f,
				// 1.1f).ease(Bounce.OUT).start(GsnTween.manager);

				// Tween.to(chat, ActorAccessor.CPOS_XY, time).target(,
				// 1.05f).ease(Expo.OUT);
				Timeline.createSequence().push(Tween.to(chat, ActorAccessor.SCALE_XY, time).target(1f, 0.8f).ease(Bounce.OUT)).push(Tween.to(chat, ActorAccessor.SCALE_XY, time).target(1f, 1f).ease(Expo.OUT))
				// .push(Tween.to(chat, ActorAccessor.SCALE_XY, time).target(1f,
				// 1.0f).ease(Expo.OUT))
						.repeat(5, 500).start(MyPoker.game.tweenManger);

				// .delay(0). start(GsnTween.manager);
				//
				// .delay(time). start(GsnTween.manager);
				// .delay(time * 2). start(GsnTween.manager);
				count++;
				break;
			// case Keys.R:
			// start();
			// break;
			case Keys.T:
				win();
				break;
			case Keys.Y:
				;
				break;
			case Keys.Z:
				// players[0].chat("trung asfasdf asdf asdf asdf asdfas asdffa");
				// players[1].chat("trung asfasdf asdf asdf asdf asdfas asdffa");

				// MyPoker.client.send(PacketFactory.createTakeChair());
				break;
			case Keys.X:
				MyPoker.client.send(PacketFactory.createBaseInfoRequest());
				break;
			case Keys.C:
				Label la = new Label("AAA", new Label.LabelStyle(pokerTexture.inst().fontLarge, new Color(1, 1, 1, 1)));
				la.x = la.y = 50;
				addActor(la);
				break;
			case Keys.V:
				pokerTexture.inst().fontLarge.setScale(2);
				la = new Label("AAA", new Label.LabelStyle(pokerTexture.inst().fontLarge, new Color(1, 1, 1, 1)));
				la.scaleX = 2;
				la.scaleY = 2;
				la.x = la.y = 100;
				addActor(la);
				break;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return super.keyDown(keycode);
	}

	public void kickRoom(int nChair, int reason) {
		if (nChair == myChair) {
			switch (reason) {
			case 0:
				((PlayScreen) screen).showHetTien();
				break;
			case 6:
				((PlayScreen) screen).showNoPlay();

			default:
				break;
			}

		} else {
			int stt = (nChair + 5 - myChair) % 5;
			players[stt].setAvailable(false);
			updateChoNguoiKhac();
			updateStartBtn();
			if (choNguoiKhacImg.visible)
				stopAutoStart();
			updateThamGiaBtn();
		}
	}

	public void newGame() {
		// init(false);

		Gdx.app.log(tag, "new game");
		if (newChair >= 0)
			tinhtienPlayer(newChair);
		newChair = -2;
		if (myChair < 0)
			viewing.visible = true;
		else
			viewing.visible = false;
		for (int i = 4; i >= 0; i--) {
			players[i].newGame();

			addActor(players[i]);

			if (i == 0 && myChair >= 0) {
				players[i].setArrow(true);
			} else {
				players[i].setArrow(false);
			}
		}
		updateChoNguoiKhac();
		updateStartBtn();
		isNewGame = true;
		// if (roomType == 1)
		// players[0].setDark(4, true);
	}

	public void newGameWhenEndGame() {
		// init(false);

		Gdx.app.log(tag, "new game end game");
		if (newChair >= 0)
			tinhtienPlayer(newChair);
		newChair = -2;
		if (myChair < 0)
			viewing.visible = true;
		else
			viewing.visible = false;

		if (!isNewGame) {
			for (int i = 4; i >= 0; i--) {
				players[i].newGame();
				addActor(players[i]);
			}
			updateChoNguoiKhac();
			updateStartBtn();
		}
		isNewGame = false;

		// if (roomType == 1)
		// players[0].setDark(4, true);
	}

	public void notifyCard(JSONArray c1, JSONArray c2, JSONArray c3) {
		try {
			for (int i = 0; i < 5; i++) {
				if (i != myChair && players[getChair(i)].isAvailable() && !players[getChair(i)].isFold()) {
					showCard(getChair(i), c1.getInt(i), c2.getInt(i), c3.getInt(i));
					System.out.println(" show card " + i);
				}
			}
		} catch (Exception e) {

		}

	}

	private void remove(Actor actor) {
		if (actor != null)
			actor.remove();
	}

	private void resetBetText() {
		updateBetText(-1, tong, 0);

	}

	public void setMyChair(int myChair) {
		this.myChair = myChair;
		if (myChair == -1) { // ngoi xem
			MyPoker.client.send(PacketFactory.createViewRequest());
			choNguoiKhacImg.visible = false;
			dotWait1.visible = false;
			dotWait2.visible = false;
			dotWait3.visible = false;
		}
	}

	public void setRoomType(int roomType) {
		this.roomType = roomType;
		// Gdx.app.log(tag, "room type : " + roomType);
		switch (roomType) {
		case 0:
			Image tmp = new Image(pokerTexture.inst().nenTapSu);
			ActorUtility.setCenter(tmp, width / 2, height * 0.75f);
			this.root.addActorAfter(nenLoai, tmp);
			nenLoai.remove();
			nenLoai = tmp;
			break;
		case 1:
			tmp = new Image(pokerTexture.inst().nenNangCao);
			ActorUtility.setCenter(tmp, width / 2, height * 0.75f);
			this.root.addActorAfter(nenLoai, tmp);
			nenLoai.remove();
			nenLoai = tmp;
			break;
		}
	}

	long[] tien = new long[5];

	public void setVisible(int chair, boolean b) {
		int stt = (chair + 5 - myChair) % 5;
		players[stt].visible = true;
	}

	public void setUserInfor(int chair, UserInfo info) {
		int stt = (chair + 5 - myChair) % 5;
		if (info == null) {
			players[stt].setAvailable(false);
			return;
		}
		
		if (stt == 0)
			DataProvider.gold = info.gold;
		tien[chair] = info.gold;
		players[stt].setUserInfo(info);
		players[stt].setAvailable(true);
		updateStartBtn();
	}

	public void showCard(int id, int card) {
		if (id != myChair) {
			players[getChair(id)].setCardID(1, card);
			players[getChair(id)].setCardID(0, 52);
		} else {
			players[getChair(id)].setCardID(1, card);
		}
	}

	private void showCard(int chair, int c1, int c2, int c3) {
		if (players[chair].cardGroup.cards[1].getId() == c2) {
			players[chair].setCardID(0, c1);
		} else if (players[chair].cardGroup.cards[1].getId() == c1) {
			players[chair].setCardID(0, c2);
		}
		if (roomType == 1)
			players[chair].setCardID(4, c3);

	}

	public void showChonQuan(int id1, int id2) {
		card1 = id1;
		card2 = id2;
		chonGroup = new ChonQuanGroup(this, id1, id2);
		ActorUtility.setCenter(chonGroup, width / 2, height / 2);
		addActor(chonGroup);
		chonGroup.color.a = 0f;
		for (Tween t : GsnTween.setTintGroup(chonGroup))
			t.target(0.2f, 0.3f, 0.1f).start(MyPoker.game.tweenManger);

		Tween.to(chonGroup, ActorAccessor.OPACITY, 1f).target(1).ease(Sine.OUT).start(MyPoker.game.tweenManger);
		for (Tween t : GsnTween.toTintGroup(chonGroup, 1f))
			t.target(1, 1, 1).ease(Sine.OUT).start(MyPoker.game.tweenManger);
	}

	public float showEff(Actor img) {
		float duration = 1.5f;
		ActorUtility.setCenter(img, width / 2, height / 2);
		addActor(img);
		img.action(Sequence.$(FadeOut.$(1.5f), Remove.$()));
		return duration;
	}

	public float showEff(Image img, float duration) {
		ActorUtility.setCenter(img, width / 2, height / 2);
		addActor(img);
		img.action(Sequence.$(FadeOut.$(1.5f), Remove.$()));
		return duration;
	}

	public void showFirstCard(int... cards) {
		if (chonGroup != null)
			chonGroup.remove();
		Gdx.app.log(tag, "show First Card: ");
		for (int i = 0; i < 5; i++) {
			Gdx.app.log(tag, " " + cards[i]);
		}
		for (int i = 0; i < 5; i++) {
			if (cards[i] != 52) {
				Gdx.app.log(tag, "dc hien" + cards[i]);
				players[(i - myChair + 5) % 5].setCardID(1, cards[i]);
				players[(i - myChair + 5) % 5].setCardID(0, 52);

			}

			// if(cards[i] != 52)
			// {
			// players[i].setCardID(1, cards[i]);
			// }
		}
		if (myChair >= 0 && cards[myChair] != 52)
			showMyFirstCard(cards[myChair]);
	}

	public void showMyFirstCard(int cardID) {
		// Gdx.app.log(tag, " 2 cay dau : " + card1 + " " + card2);
		// Gdx.app.log(tag, " cay lat : " + cardID);
		players[0].setDark(0, true);
		if (cardID == card1)
			players[0].setCardID(0, card2);
		else
			players[0].setCardID(0, card1);

	}

	public void showPublicCard(JSONObject json) {
		try {
			JSONArray card1 = json.getJSONArray("card1");
			JSONArray card2 = json.getJSONArray("card2");
			for (int i = 0; i < 5; i++) {
				int tmp1 = card1.getInt((i + myChair) % 5);
				int tmp2 = card2.getInt((i + myChair) % 5);
				if (tmp1 == 52)
					continue;
				if (players[i].getCardID(1) == tmp1)
					players[i].setCardID(0, tmp2);
				else
					players[i].setCardID(0, tmp1);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void updateStartBtn() {
		if (!inGame && owner == myChair && getNumberPlayer() >= 3) {
			addActor(startBtn);
			choNguoiKhacImg.visible = false;
		} else
			startBtn.remove();
	}

	public void start(JSONObject json) {
		Gdx.app.log(tag, "Game Start");
		// Image effStart = new Image(PokerTexture.effStart);
		inGame = true;
		PokerSound.playStartGame();

		if (countClock != null)
			countClock.remove();
		if (startGame != null)
			startGame.remove();
		if (betText != null)
			betText.visible = true;
		startBtn.remove();
		remove(chonGroup);

		if (myChair >= 0)
			viewBtn.visible = false;
		else
			viewBtn.visible = true;
		for (int i = 0; i < 5; i++)
			players[i].newGame();
		try {
			JSONArray chip = json.getJSONArray("playerChip");
			JSONArray b = json.getJSONArray("players");
			long minbet = json.getLong("minBet");
			int count = 0;
			for (int i = 0; i < 5; i++) {
				if (b.getBoolean(i)) {
					players[getChair(i)].updateMoney(chip.getLong(i));
					count++;

				}
			}
			tong = minbet * count;
			chia2LaDau();
			updateBetText(-1, tong, 0);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void stopAutoStart() {
		if (countClock != null)
			countClock.remove();
		if (startGame != null)
			startGame.remove();
	}

	public void stopTime() {
		for (int i = 0; i < 5; i++)
			players[i].stopTime();
	}

	private void updateBetText(int from, final long tong, long theo) {
		if (betText != null) {
			// betText.remove();
			betText.update(tong, theo);
		}
		this.tong = tong;
		// betText = new BetTextGroup(tong, theo);
		// ActorUtility.setRatio(betText, 0.5f, 1f, width / 2, height / 2);
		// addActor(betText);

		MyPoker.game.call(new TweenCallback() {

			@Override
			public void onEvent(EventType type, BaseTween source) {
				// TODO Auto-generated method stub
				chipGroup.setMoney(tong);
			}
		}, 0.3F);

		if (from < 0)
			return;

		ChipRandomGroup ani = new ChipRandomGroup(theo);
		ani.x = players[from].x + players[from].width / 2;
		ani.y = players[from].y + players[from].height / 2;

		// ani.action(Sequence.$(MoveTo.$(chipGroup.x, chipGroup.y, 0.2f),
		// Remove.$()));
		float time = 0.5f;
		Timeline.createParallel().push(Tween.to(ani, ActorAccessor.POS_XY, time).target(chipGroup.x, chipGroup.y).ease(Quart.OUT)).start(MyPoker.game.tweenManger);
		MyPoker.game.remove(ani, time);
		addActor(ani);
	}

	private void updateBtn(int turnType) {
		for (int i = 0; i < 8; i++)
			btnArr[i].setEnable(true);
		switch (turnType) {
		case 0:
			btnArr[2].setEnable(false);
			btnArr[0].setEnable(false);
			break;
		case 1:
			btnArr[1].setEnable(false);
			btnArr[4].setEnable(false);
			break;
		case 2:
			btnArr[0].setEnable(false);
			btnArr[4].setEnable(false);
			btnArr[7].setEnable(false);
			btnArr[6].setEnable(false);
			btnArr[5].setEnable(false);
			btnArr[2].setEnable(false);
			break;
		case 3:
			btnArr[2].setEnable(false);
			btnArr[4].setEnable(false);
			btnArr[1].setEnable(false);
			break;
		}
	}

	public void updateMoney(final JSONObject json) {

		MyPoker.game.call(new TweenCallback() {

			@Override
			public void onEvent(EventType type, BaseTween source) {
				try {
					final int nChair = json.getInt("nChair");
					final long bean = json.getLong("bean");
					players[getChair(nChair)].updateMoney(bean);
					if (nChair == myChair) {
						DataProvider.gold = bean;
					}
					// TODO Auto-generated method stub
					effectMoney(nChair, bean - tien[nChair]);
					tien[nChair] = bean;
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		}, 3f);
	}

	public void updateRoomOwner(int nChair) {
		owner = nChair;

		int i;
		for (i = 0; i < 5; i++) {
			players[getChair(i)].boss.visible = false;
			Gdx.app.log("Gan bang fale", "kjdf ");
		}
		players[getChair(owner)].boss.visible = true;
		Gdx.app.log("Gan bang true", "kjdf ");
		updateStartBtn();
	}

	public void userExit(int chair, int id) {
		if (chair < 0) {
			removeViewer(id);

			for (int i = 0; i < players.length; i++) {
				if (players[i].info != null && players[i].info.id == id) {
					players[i].viewToUser = false;
					players[i].avatar.visible = false;
					players[i].info = null;
				}
			}

			return;
		}
		int stt = (chair + 5 - myChair) % 5;
		System.out.println(" " + stt);
		players[stt].setAvailable(false);
		players[stt].viewToUser = false;
		updateChoNguoiKhac();
		updateStartBtn();

		if (choNguoiKhacImg.visible)
			stopAutoStart();
		updateThamGiaBtn();
	}

	public void userExit(int id) {

		for (int i = 0; i < players.length; i++) {
			if (players[i] != null && players[i].info != null && players[i].info.id == id) {

				players[i].setAvailable(false);
				players[i].viewToUser = false;
				updateChoNguoiKhac();
				updateStartBtn();

				if (choNguoiKhacImg.visible)
					stopAutoStart();
				updateThamGiaBtn();

			}
			else
			{
				if(players[i].info == null)
					System.out.println("in fo null moi VKLLLL");
				else
					System.out.println(players[i].info.id);
			}
		}

	}

	private void updateChoNguoiKhac() {

		choNguoiKhacImg.visible = (!inGame && (getNumberPlayer() < 3));
		dotWait1.visible = choNguoiKhacImg.visible;
		dotWait2.visible = choNguoiKhacImg.visible;
		dotWait3.visible = choNguoiKhacImg.visible;
	}

	public void view(JSONObject json) {
		try {
			choNguoiKhacImg.visible = false;
			dotWait1.visible = false;
			dotWait2.visible = false;
			dotWait3.visible = false;
			JSONArray playerState = json.getJSONArray("playerState");

			boolean ok = false;
			JSONArray cardID = json.getJSONArray("cardID");
			for (int i = 0; i < 25; i++) {
				int tmp = cardID.getInt(i);
				if (tmp > 0)
					ok = true;
			}

			for (int i = 0; i < 5; i++)
				players[i].cardGroup.numIsDeal = 0;

			if (ok)
				for (int i = 0; i < 25; i++) {
					int tmp = cardID.getInt(i);
					int id = i % 5;
					if (tmp != -1) {
						players[getChair(id)].cardGroup.numIsDeal++;
						players[getChair(id)].addCardID(tmp);
					}
				}
			for (int i = 0; i < 5; i++) {
				if (playerState.getBoolean(i))
					players[getChair(i)].fold();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void win() {
		Gdx.app.log(tag, "win");
		PokerSound.playThang();
		// float duration = showEff(new Image(PokerTexture.effectThang));
		players[0].timBo();

		MyPoker.game.call(new TweenCallback() {

			@Override
			public void onEvent(EventType type, BaseTween source) {
				effectThang(players[0].groupType, players[0].group);
			}
		}, 1f);
	}

	public void effectThang(final int type, final CardGroupLogic logic) {

		final Image bg = new Image(pokerTexture.inst().BgAlpha);
		bg.width = width;
		bg.height = height;
		addActor(bg);
		final Group a = new WinEffGroup(type, logic);
		ActorUtility.setCenter(a, width / 2, height / 2);
		addActor(a);
		float f = 0.4f;
		for (Tween t : GsnTween.toTintGroup(a, 0.5f))
			t.target(f, f, f).ease(Cubic.INOUT).repeatYoyo(10, -1).start(MyPoker.game.tweenManger);
		float time = 3f;
		MyPoker.game.remove(a, time);
		MyPoker.game.remove(bg, time);

		// Actor tmp = new Image(PokerTexture.effectThang);
		// Tween.to(tmp, ActorAccessor.TINT, 1f).target(0.2f, 0.2f,
		// 0.2f).ease(Cubic.INOUT).repeatYoyo(-1, -1).start(GsnTween.manager);
		// addActor(tmp);

	}

	public void jackpot(JSONObject json) {
		try {
			int roomID = json.getInt("roomID");
			String name = json.getString("username");
			long jackpot = json.getLong("jackpot");
			int uid = json.getInt("userID");
			Gdx.app.log(tag, " jackpot : " + uid + " " + UserData.myId);
			if (uid == UserData.myId)
				effectJackpot(jackpot);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void effectJackpot(long jackpot) {
		Gdx.app.log(tag, "nhan jackpot : " + jackpot);
		PokerSound.playJackpot();
		RotationGroup group = new RotationGroup(pokerTexture.inst().nenJackpot, pokerTexture.inst().jackpot, "removeImg");
		group.action(Delay.$(Remove.$(), 3f));
		ActorUtility.setRatio(group, 0.5f, 0.5f, width / 2, height / 2);
		addActor(group);

		// final int chair = getChair(myChair);
		// ChipRandomGroup ani = new ChipRandomGroup(jackpot);
		// ani.x = chipGroup.x;
		// ani.y = chipGroup.y;
		// ani.action(Sequence.$(MoveTo.$(players[chair].x +
		// players[chair].width / 2, players[chair].y + players[chair].height /
		// 2, 1f), Remove.$()));
		// addActor(ani);

		GsnParticleActor jack = new GsnParticleActor(pokerTexture.inst().jackpotEff);
		jack.setPostition(width / 2, height * 0.63f);
		jack.start();
		// jack.removeAfter(1f);
		addActor(jack);
	}

	GsnNormalButton[] thamgiaBtn = new GsnNormalButton[5];

	public void takeChairResult(boolean success) {
		System.out.println("hide tacke chair " + success);
		if (success)
			hideTakeChairBtn();
	}

	public void hideTakeChairBtn() {
		System.out.println("an het con me luon");
		for (int i = 0; i < thamgiaBtn.length; i++)
			if (thamgiaBtn[i] != null)
				thamgiaBtn[i].remove();
	}

	public void updateThamGiaBtn() {
		if (myChair >= 0 || meViewToUser)
			return;

		System.out.println("Me view to user " + meViewToUser);

		for (int i = 0; i < 5; i++) {
			if (thamgiaBtn[i] != null) {
				thamgiaBtn[i].remove();

			} else {
				thamgiaBtn[i] = new GsnNormalButton(TAKE_CHAIR, pokerTexture.inst().joinBtn, pokerTexture.inst().joinBtnDown);
				if (i == 0 || i == 3 || i == 4) {
					thamgiaBtn[i].x = players[i].x + thamgiaBtn[i].width / 10;
					thamgiaBtn[i].y = players[i].y + players[i].height / 2 - thamgiaBtn[i].height / 2;
				} else {
					thamgiaBtn[i].x = players[i].x + players[i].width - thamgiaBtn[i].width * 0.9f;
					thamgiaBtn[i].y = players[i].y + players[i].height / 2 - thamgiaBtn[i].height / 2;
				}
			}
			thamgiaBtn[i].id = getID(i);
			thamgiaBtn[i].setClickListener(new ClickListener() {

				@Override
				public void click(Actor actor, float x, float y) {
					hideTakeChairBtn();
					MyPoker.client.send(PacketFactory.createTakeChair(((GsnNormalButton) actor).id));
				}
			});
			// ActorUtility.set(thamgiaBtn[i], players[i].x + players[i].width /
			// 2, players[i].y + players[i].height / 2);

			if (!players[i].isAvailable() && !players[i].viewToUser) {
				addActor(thamgiaBtn[i]);
				System.out.println("DKM " + players[i].isAvailable() + " " + players[i].viewToUser);
			}

		}
		if (choNguoiKhacImg != null) {
			boolean show = choNguoiKhacImg.visible;
			choNguoiKhacImg.remove();
			addActor(choNguoiKhacImg);
			choNguoiKhacImg.visible = show;
		}
	}

	boolean joinedRoom = false;
	public JSONObject jsonJoinRoom;

	public void joinRoomSuccess(JSONObject json) {
		try {
			MyPoker.game.tweenManger.killAll();
			myChair = json.getInt("myChair");
			setMyChair(myChair);
			JSONArray playerStatus = json.getJSONArray("playerStatus");
			JSONArray playerList = json.getJSONArray("playerList");
			int roomType = json.getInt("roomType");
			roomIndex = json.getInt("roomIndex");
			int roomOwner = json.getInt("roomOwnerID");
			labelRoomIndex.setText("Bàn : " + roomIndex);

			setRoomType(roomType);
			init(true);
			// updateChoNguoiKhac();
			updateRoomOwner(roomOwner);
			for (int i = 0; i < 5; i++)
				if (playerStatus.getInt(i) > 0) {
					// ==2 là đã sẵn sàng, 1 là chưa sẵn sàng
					JSONObject jp = playerList.getJSONObject(i);
					String name = jp.getString("uName");
					String avatar = jp.getString("avtURL");
					long gold = jp.getLong("bean");
					int uid = jp.getInt("uId");
					UserInfo info = new UserInfo();
					info.name = name;
					info.id = uid;
					info.gold = gold;
					info.avatar = avatar;
					setUserInfor(i, info);
				} else
					setUserInfor(i, null);
			// dang xem
			// updateThamGiaBtn();

			// if (json.getBoolean("isAutoStartGame")) {
			// // autoStartCountDown
			// int remain = json.getInt("autoStartCountDown");
			// autoStart(remain);
			// } else {
			//
			// }

			// MyPoker.client.send(PacketFactory.createBaseInfoRequest());
			if (betInfo != null)
			// betInfo.remove();
			{
				betInfo.updateMoney(json.getLong("roomBet"));
			}
			// addActor(betInfo);
			// ActorUtility.setRatio(betInfo, 0, 0.3f, logo.x + logo.width *
			// 1.3f, logo.y + (logo.height - betInfo.height) / 2);

			// JSONArray nameArr = json.getJSONArray("nameViewer");
			// JSONArray stateArr = json.getJSONArray("stateViewer");
			// JSONArray chairArr = json.getJSONArray("nChair");
			// List<String> listName = new ArrayList<String>();
			// List<Boolean> listState = new ArrayList<Boolean>();
			// for (int i = 0; i < nameArr.length(); i++) {
			// if (nameArr.isNull(i))
			// continue;
			// listName.add(nameArr.getString(i));
			// listState.add(stateArr.getBoolean(i));
			//
			// if (chairArr.getInt(i) >= 0 && stateArr.getBoolean(i)) {
			// players[getChair(chairArr.getInt(i))].viewToUser = true;
			// if (thamgiaBtn[getChair(chairArr.getInt(i))] != null) {
			// thamgiaBtn[getChair(chairArr.getInt(i))].visible = false;
			// }
			// }
			// }
			//
			// viewListGroup.update(listName, listState);
			// viewBtn.updateText(listName.size() + "");

			JSONArray viewerList = json.getJSONArray("viewerList");
			JSONArray viewerState = json.getJSONArray("viewerState");
			JSONArray regChair = json.getJSONArray("regChair");

			List<String> listName = new ArrayList<String>();
			List<Boolean> listState = new ArrayList<Boolean>();
			List<Integer> listID = new ArrayList<Integer>();
			meViewToUser = false;
			for (int i = 0; i < 9; i++) {
				if (!viewerList.isNull(i)) {
					JSONObject playerInfo = viewerList.getJSONObject(i);
					listID.add(playerInfo.getInt("uId"));
					listName.add(playerInfo.getString("uName"));
					int reg = regChair.getInt(i);
					listState.add(reg >= 0);
					UserInfo userInfo = new UserInfo();
					userInfo.avatar = playerInfo.getString("avtURL");
					userInfo.gold = playerInfo.getLong("bean");
					userInfo.id = playerInfo.getInt("uId");
					userInfo.name = playerInfo.getString("uName");
					viewerListInfo.add(userInfo);
					if (reg >= 0) {
						players[getChair(reg)].viewToUser = true;

						players[getChair(reg)].setUserInfo(userInfo);

						if (thamgiaBtn[getChair(reg)] != null)
							thamgiaBtn[getChair(reg)].remove();
						if (playerInfo.getInt("uId") == UserData.myId) {
							takeChairResult(true);
							meViewToUser = true;
						}
					}

				}
			}

			// viewListGroup.update(listID, listName, listState);
			viewBtn.updateText(listName.size() + "");
			viewBtn.size = listName.size();
			updateThamGiaBtn();
			if (myChair >= 0)
				viewBtn.visible = false;
			else
				viewBtn.visible = true;

		} catch (JSONException ex) {
			ex.printStackTrace();
		}
	}

	public void allCard(JSONObject json) {
		try {
			int num = json.getInt("nCards");
			int chair = json.getInt("Chair");
			JSONArray cards = json.getJSONArray("Cards");
			int[] card = new int[num];
			for (int i = 0; i < num; i++)
				card[i] = cards.getInt(i);
			players[0].cardGroup.arrow.visible = false;
			players[getChair(chair)].allCard(card);
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void tinhtienPlayer(int moi) {
		Gdx.app.log(tag, " chair Cu : " + myChair);
		Gdx.app.log(tag, " chair Moi : " + moi);

		UserInfo[] info = new UserInfo[5];
		boolean[] boss = new boolean[5];
		for (int i = 0; i < 5; i++) {
			info[i] = new UserInfo();
			PlayerGroup p = players[getChair(i)];
			info[i].available = p.available;
			info[i].avatar = p.avatar.avatarUrl;
			info[i].id = p.id;
			info[i].gold = p.getMoney();
			info[i].name = p.avatar.name;
			boss[i] = p.boss.visible;
		}

		myChair = moi;

		for (int i = 0; i < 5; i++) {
			players[getChair(i)].setUserInfo(info[i]);
			players[getChair(i)].setAvailable(info[i].available);
			players[getChair(i)].boss.visible = boss[i];
		}

	}

	public int newChair = -2;

	public void updateUserInNewGame(JSONObject json) {
		try {
			JSONObject playerInfo = json.getJSONObject("playerInfo");
			int chair = json.getInt("chair");
			long playerChip = json.getLong("playerChip");
			int uid = json.getInt("viewID");

			players[getChair(chair)].newGame();
			players[getChair(chair)].setAvailable(true);

			UserInfo userInfo = new UserInfo();
			userInfo.avatar = playerInfo.getString("avtURL");
			userInfo.gold = playerInfo.getLong("bean");
			userInfo.id = playerInfo.getInt("uId");
			userInfo.name = playerInfo.getString("uName");
			players[getChair(chair)].setUserInfo(userInfo);

			// viewListGroup.remove(userInfo.name);
			for (int i = 0; i < viewerListInfo.size(); i++) {
				if (viewerListInfo.get(i).id == userInfo.id) {
					viewerListInfo.remove(i);
					viewBtn.size--;
					break;
				}
			}

			viewBtn.updateText("" + viewBtn.size);

			if (UserData.myId == uid) {
				if (myChair < 0) {
					// myChair += 5;
					// tinhtienPlayer(chair);
					newChair = chair;
					if (inAutoStart) {
						tinhtienPlayer(newChair);
						viewing.visible = false;
						if (myChair >= 0)
							viewBtn.visible = false;
						else
							viewBtn.visible = true;
						players[0].setArrow(true);
					}
				}
			}
		} catch (JSONException ex) {
			ex.printStackTrace();
		}
	}

	public Group getRoot() {
		return this.root;
	}

	@Override
	public void draw() {
		// TODO Auto-generated method stub
		if (choNguoiKhacImg != null && choNguoiKhacImg.visible) {
			// Gdx.app.log("count dot ", countDot + " **  ");
			if (countDot == 5) {
				dotWait2.visible = true;

			} else if (countDot == 10) {
				dotWait3.visible = true;

			} else if (countDot == 15) {

				dotWait2.visible = false;
				dotWait3.visible = false;
				countDot = 0;
			}
			countDot++;

		} else {
			dotWait2.visible = dotWait1.visible = dotWait3.visible = false;
		}

		if (viewing != null && viewing.visible) {
			// Gdx.app.log("count dot ", countDot + " **  ");
			if (countDotView == 5) {
				dotView2.visible = true;

			} else if (countDotView == 10) {
				dotView3.visible = true;

			} else if (countDotView == 15) {

				dotView2.visible = false;
				dotView3.visible = false;
				countDotView = 0;
			}
			countDotView++;

		} else {
			dotView2.visible = dotView1.visible = dotView3.visible = false;
		}

		super.draw();
	}

	public void addViewer(int id, String name, long gold, String avatar, boolean state) {
		// TODO Auto-generated method stub
		// viewListGroup.add(id, name, state);
		UserInfo u = new UserInfo();
		u.id = id;
		u.name = name;
		u.gold = gold;
		u.avatar = avatar;
		viewerListInfo.add(u);
		viewBtn.size++;
		viewBtn.updateText(viewBtn.size + "");
	}

	public void removeViewer(int id) {
		// viewListGroup.remove(id);
		for (int i = 0; i < viewerListInfo.size(); i++) {
			if (viewerListInfo.get(i).id == id) {
				viewerListInfo.remove(i);
				viewBtn.size--;
				break;
			}
		}

		viewBtn.updateText(viewBtn.size + "");

	}

	public void viewToUser(int chair) {
		players[getChair(chair)].viewToUser = true;

	}

	public void setViewRegUser(int regChair, UserInfo info) {
		// TODO Auto-generated method stub
		players[getChair(regChair)].setUserInfo(info);
		players[getChair(regChair)].viewToUser = true;

		for (int i = 0; i < players.length; i++)
			System.out.println("trang thai " + players[i].isAvailable());
	}

	public void regSuccess(int myId, int chair) {
		// TODO Auto-generated method stub
		for (int i = 0; i < viewerListInfo.size(); i++) {
			if (viewerListInfo.get(i).id == myId) {
				players[getChair(chair)].viewToUser = true;
				players[getChair(chair)].setUserInfo(viewerListInfo.get(i));

				// neu gan cho nay = false -> nguoi vao dang ki tham gia ko hien
				// duoc bo bai

				if (thamgiaBtn[getChair(chair)] != null)
					thamgiaBtn[getChair(chair)].remove();
			}
		}
	}

	public void onBackPress() {
		// TODO Auto-generated method stub
		if (inGame && myChair >= 0)
			((PlayScreen) screen).showQuitDlg();
		else {
			MyPoker.client.send(PacketFactory.createQuitRoom());
			MyPoker.game.setChooseRoomScreen();
			MyPoker.client.send(PacketFactory.getRefreshListTable());
		}
	}
}
